//
//  FAIDFARequest.swift
//  flutter_auto_track
//
//  Created by leonard on 2024/6/6.
//

import Foundation
import AdSupport
import AppTrackingTransparency

class FAIDFARequest {
    
    static let idfaCacheKey = "com.auto.track.idfa"
    static var timer: Timer?
    
    /// 获取idfa
    /// iOS 14以上需要获取权限，根据requestPermission判断是否请求
    static func idfaPermission(arguments: Any?, callback: @escaping ((String)->())) {
        var requestPermission = true
        if let trackArguments = arguments as? [String: Any],
           let request = trackArguments["requestPermission"] as? Bool {
            requestPermission = request
        }
        if let idfaStr = UserDefaults.standard.value(forKey: idfaCacheKey) as? String {
            callback(idfaStr)
            return
        }
        if #available(iOS 14, *) {
            if (!requestPermission) {
                callback("")
                return
            }
            ATTrackingManager.requestTrackingAuthorization(){ _ in}
            if timer == nil {
                ///ios17的系统用户操作没有回调
                timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { t in
                    switch ATTrackingManager.trackingAuthorizationStatus {
                    case .authorized:
                        t.invalidate()
                        let idfaStr = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                        UserDefaults.standard.setValue(idfaStr, forKey: idfaCacheKey)
                        callback(idfaStr)
                    case .denied, .restricted:
                        t.invalidate()
                        callback("")
                    default:
                        break
                    }
                }
            }
        } else {
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                let idfaStr = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                UserDefaults.standard.setValue(idfaStr, forKey: idfaCacheKey)
                callback(idfaStr)
            } else {
                callback("")
            }
        }
    }
    
}
